package cn.autumnorange.app.common.consumer.rpc.feign;

import cn.autumnorange.app.common.rpc.RPCWrapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/** 发起请求时的拦截器 */
@Slf4j
@Configuration
public class FeignHeaderInterceptor implements RequestInterceptor {

  @Override
  public void apply(RequestTemplate requestTemplate) {
    HttpServletRequest request = RPCWrapper.getHttpServletRequestRPCWrapper();
    //    改为自定义的request HttpServletRequestHeaderWrapper里面有可自定义的header信息
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        if (name.equalsIgnoreCase("content-length")) {
          continue;
        }
        String values = request.getHeader(name);
        requestTemplate.header(name, values);
        //        log.info("headerName:" + name + "    value:" + values);
      }
    }
    //    没有覆盖原方法多次写入参数值。。。
    //    Enumeration<String> bodyNames = request.getParameterNames();
    //    StringBuffer body = new StringBuffer();
    //    if (bodyNames != null) {
    //      while (bodyNames.hasMoreElements()) {
    //        String name = bodyNames.nextElement();
    //        String values = request.getParameter(name);
    //        body.append(name).append("=").append(values).append("&");
    //      }
    //    }
    //    if (body.length() != 0) {
    //      body.deleteCharAt(body.length() - 1);
    //      requestTemplate.body(body.toString());
    //      LOGGER.info("feign interceptor body:{}", body.toString());
    //    }
  }
}
